//
//  TablePrinter.m
//  Objective-C
//
//  Created by 林世木 on 11-11-10.
//  Copyright (c) 2011年 lsray. All rights reserved.
//

#import "TablePrinter.h"
#import "TablePrinterDataSource.h"

@implementation TablePrinter
@synthesize dataSource;

- (void) printTable
{
    NSString* separator = @"-------------";
    NSString* title = @"Table";
    
    if ([dataSource respondsToSelector: @selector(tableTitle)]) {  
        //编译器会抱怨respondsToSelector:不是协议<TableDataSource>的一部分
        //明确告诉编译器，dataSource是NSObject的一个子类
        title = [dataSource tableTitle];
    }
    printf("\n%s\n%s\n",[title UTF8String],[separator UTF8String]);
    
    int numRows = [dataSource numberOfRowsInTable];
    int j;
    BOOL printLineNumbers = NO;
    
    if ([dataSource respondsToSelector: @selector(printLineNumbers)]) {
        printLineNumbers = [dataSource printLineNumbers];
    }
    
         for (j=0; j < numRows; j++){
             NSString* outputString = [dataSource stringForRowAtIndex:j];
             if (printLineNumbers) {
                 printf("%d | %s\n",j+1, [outputString UTF8String]);
             } else {
                 printf("%s\n",[outputString UTF8String]);
             }
         }
}

@end
